<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryParams" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="食品品种" prop="title">
                <el-input v-model="queryParams.title" placeholder="输入食品品种"> </el-input>
            </el-form-item>
            <el-form-item label="自查日期" prop="title">
                <el-date-picker :editable="false" clearable v-model="queryParams.date" type="date"
                    value-format="yyyy-MM-dd" placeholder="选择自查日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['Laboratory_fsc:foodsafe:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                    v-hasPermi="['Laboratory_fsc:foodsafe:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                    @click="handleDelete" v-hasPermi="['Laboratory_fsc:foodsafe:delete']">删除</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="analysisProductList" @selection-change="handleSelectionChange"
            max-height="550">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="食品品种" align="center" prop="title">
                <template slot-scope="scope">
                    <span style="color:rgba(213, 241, 255, 0.8)">{{ scope.row.title || '- -' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="自查日期" align="center" prop="date">
                <template slot-scope="scope">
                    <span style="color:rgba(213, 241, 255, 0.8)">{{ scope.row.date || '- -' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="食品安全员" align="center" prop="aqy">
                <template slot-scope="scope">
                    <span style="color:rgba(213, 241, 255, 0.8)">{{ scope.row.aqy || '- -' }}</span>
                </template>

            </el-table-column>
            <el-table-column label=" 基地负责人" align="center" prop="fzr">
                <template slot-scope="scope">
                    <span style="color:rgba(213, 241, 255, 0.8)">{{ scope.row.fzr || '- -' }}</span>
                </template>

            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-bottom"
                        @click="excelhandleView(scope.row)">导出</el-button>
                    <el-button v-hasPermi="['Laboratory_fsc:foodsafe:query']" size="mini" type="text"
                        icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['Laboratory_fsc:foodsafe:edit']" v-if="scope.row.status <= 0">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['Laboratory_fsc:foodsafe:delete']">删除</el-button>
                    <el-popconfirm confirm-button-text='确定' @confirm="handleVerify(scope.row)" cancel-button-text=' 取消 '
                        icon="el-icon-info" icon-color="yellow" title="确认要审批此条数据吗？"
                        v-hasPermi="['Laboratory_fsc:foodsafe:verify']" v-if="scope.row.status <= 0">
                        <el-button size="mini" style="margin-left: 10px;" type="text" icon="el-icon-circle-check"
                            slot="reference">审批</el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改仰口生产报对话框 -->
        <!--  <el-dialog fullscreen :title="title" :visible.sync="open" width="700px" append-to-body> -->
        <el-dialog fullscreen :title="title" :visible.sync="open" width="700px" append-to-body custom-class="myDialog">
            <TableHeader2 :data="{
                mainTitle: '食品生产企业每日食品安全检查记录',
                company: '',
                code: '',
            }" />
            <el-form ref="form" :model="form" :rules="rules" label-width="90px" class="safetyRecord_form">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="食品品种" prop="title">
                            <el-input v-model="form.title" placeholder="请输入食品品种" :disabled="openDisabled" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" :offset="12">
                        <el-form-item label="自查日期" prop="date">
                            <el-date-picker :editable="false" clearable size="small" v-model="form.date" type="date"
                                value-format="yyyy-MM-dd" placeholder="选择自查日期" :disabled="openDisabled">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <br />
                <el-divider content-position="center">食品安全检查记录子信息</el-divider>
                <el-table class="noGao" :data="subList" :span-method="arraySpanMethod" border
                    style="width: 100%;margin-top: 30px;">
                    <el-table-column align="center" prop="category" label="检查项目" width="180">
                    </el-table-column>
                    <el-table-column width="100" align="center" prop="order" label="项目序号"></el-table-column>
                    <el-table-column width="920" align="center" prop="activityName" label="日检查内容">
                    </el-table-column>
                    <el-table-column minWidth="200" align="center" prop="result" label="评价">
                        <template slot-scope="scope">
                            <el-select :disabled="openDisabled" v-model="scope.row.result" placeholder="请选择">
                                <el-option label="是" :value="1">
                                </el-option>
                                <el-option label="否" :value="0">
                                </el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column minWidth="200" align="center" prop="desc" label="描述">
                        <template slot-scope="scope">
                            <el-input :disabled="openDisabled" v-model="scope.row.desc" placeholder="请输入"
                                type="textarea">
                            </el-input>
                        </template>
                    </el-table-column>
                    <el-table-column minWidth="200" align="center" prop="remark" label="备注">
                        <template slot-scope="scope">
                            <el-input :disabled="openDisabled" v-model="scope.row.remark" placeholder="请输入"
                                type="textarea">
                            </el-input>
                        </template>
                    </el-table-column>
                </el-table>
                <el-row :gutter="24">
                    <el-col :span="24">
                        <el-form-item label="其他问题" prop=" other">
                            <el-input v-model="form.other" placeholder="其他问题" type="textarea"
                                :disabled="openDisabled" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="安全员" prop="aqy">
                            <el-input readonly v-model="form.aqy" placeholder="" :disabled="openDisabled" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" :offset="12" v-if="title=='修改食品生产企业每日食品安全检查记录'">
                        <el-form-item label="基地负责人" prop="fzr">
                            <el-input readonly v-model="form.fzr" placeholder="" :disabled="openDisabled" />
                        </el-form-item>
                    </el-col>

                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer" v-if="!openDisabled">
                <el-button type="primary" @click="submitForm" :disabled="btn_loading">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>

    import {
        listFoodSafe,
        getFoodSafe,
        delFoodSafe,
        verifyFoodSafe,
        addFoodSafe,
        updateFoodSafe,
    } from "@/api/quality/laboratory/safetyRecord";
    import TableHeader2 from "@/components/table/tableData/header2.vue";
    import JSON from './json.js'
    import { getInfo } from "@/api/login";
    import { listUser } from "@/api/system/user";
    export default {
        components: { TableHeader2 },
        name: "safetyRecord",
        data() {
            return {
                nickName: null,
                //弹窗是否禁止编辑
                openDisabled: true,
                // 遮罩层
                loading: false,
                //添加修改按钮状态
                btn_loading: false,
                // 选中数组
                ids: [],
                // 非单个禁用
                single: true,
                // 非多个禁用
                multiple: true,
                // 显示搜索条件
                showSearch: true,
                // 总条数
                total: 0,
                // 食品生产企业每日食品安全检查记录格数据
                analysisProductList: [],
                // 弹出层标题
                title: "",
                // 是否显示弹出层
                open: false,
                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 50,
                    title: null,
                    date: null,
                },
                // 表单参数
                form: {
                },
                subList: [],
                // 表单校验
                rules: {
                    title: [{ required: true, message: "不能为空" }],
                    date: [{ required: true, message: "不能为空" }],
                }
            };
        },
        created() {
            this.queryUserList()
            // 二次处理数据
            this.subList = this.handleTableArr(JSON);
            this.getList();
        },
        methods: {
            /* 查询用户列表 */
            queryUserList() {
                getInfo().then((response) => {
                    this.nickName = response.user.nickName;
                });
            },
            /** 查询仰口生产报列表 */
            getList() {
                this.loading = true;
                listFoodSafe(this.queryParams).then((response) => {
                    if (response.code == 200) {
                        this.analysisProductList = response.rows;
                        this.total = response.total;
                        this.loading = false;
                    } else {
                        this.$message.error('列表加载失败');
                    }
                }).catch((err) => {
                    this.loading = false;
                    // this.$message.error('列表加载失败')
                });
                // $axios({
                //     method: 'get',
                //     url: '/zyk/foodSafe/list',
                //     params: this.queryParams, // 请求参数拼接在url上
                // }).then(({ data }) => {
                //     //请求成功，触发then中的函数
                //     this.loading = false;
                //     if (data.code == 200) {
                //         this.analysisProductList = data.rows;
                //         this.total = data.total;

                //     } else {
                //         this.$message.error('列表加载失败');
                //     }
                // }).catch((err) => {
                //     this.loading = false;
                //     this.$message.error('列表加载失败')
                // });

            },

            // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
            },
            // 表单重置
            reset() {
                this.form = {
                    id: null,
                    title: null,
                    date: null,
                };
                this.resetForm("form");
            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.queryParams.pageNum = 1;
                this.getList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                // this.resetForm("queryParams");
                this.queryParams = {
                    title: null,
                    date: null,
                    pageNum: 1,
                    pageSize: 50,
                };
                this.handleQuery();
            },
            // 多选框选中数据
            handleSelectionChange(selection) {
                this.ids = selection.map((item) => item.id);
                this.single = selection.length !== 1;
                this.multiple = !selection.length;
            },
            /** 新增按钮操作 */
            handleAdd() {
                this.reset();
                this.form.aqy = this.nickName
                this.openDisabled = false;
                this.open = true;
                this.subList = this.handleTableArr(JSON);
                this.title = "添加食品生产企业每日食品安全检查记录";
            },
            /** 修改按钮操作 */
            handleUpdate(row) {
                this.reset();
                this.openDisabled = false;
                const id = row.id || this.ids;
                getFoodSafe(id).then((response) => {
                    this.btn_loading = false
                    if (response.code == 200) {
                        this.title = "修改食品生产企业每日食品安全检查记录";
                        this.open = true;
                        this.form = response.data
                        let subList = response.data.subList
                        for (let items of this.subList) {
                            for (let item of subList) {
                                if (items.key == item.key) {
                                    items.desc = item.desc
                                    items.remark = item.remark
                                    items.result = item.result
                                }
                            }
                        }
                        // this.form.subList = this.subList
                        this.$forceUpdate()
                    } else {
                        this.$message.error('查询失败');
                    }
                }).catch((err) => {
                    // this.$message.error('查询失败');
                })
                // $axios({
                //     method: 'get',
                //     url: '/zyk/foodSafe/' + id,

                // }).then(({ data }) => {
                //     this.btn_loading = false
                //     if (data.code == 200) {
                //         this.open = true;
                //         this.form = data.data
                //         let subList = data.data.subList
                //         for (let items of this.subList) {
                //             for (let item of subList) {
                //                 if (items.key == item.key) {
                //                     items.desc = item.desc
                //                     items.remark = item.remark
                //                     items.result = item.result
                //                 }
                //             }
                //         }
                //         // this.form.subList = this.subList
                //         this.$forceUpdate()
                //     } else {
                //         this.$message.error('查询失败');
                //     }
                // }).catch((err) => {
                //     this.$message.error('查询失败');
                // })
            },
            /** 查看按钮 */
            handleView(row) {
                this.reset();
                this.openDisabled = true;
                const id = row.id || this.ids;
                getFoodSafe(id).then((response) => {
                    this.btn_loading = false
                    if (response.code == 200) {
                        this.title = "添加食品生产企业每日食品安全检查记录";
                        this.open = true;
                        this.form = response.data
                        let subList = response.data.subList
                        for (let items of this.subList) {
                            for (let item of subList) {
                                if (items.key == item.key) {
                                    items.desc = item.desc
                                    items.remark = item.remark
                                    items.result = item.result
                                }
                            }
                        }
                        // this.form.subList = this.subList
                        this.$forceUpdate()
                    } else {
                        this.$message.error('查询失败');
                    }
                }).catch((err) => {
                    // this.$message.error('查询失败');
                })
            },
            /** 提交按钮 */
            submitForm() {
                this.$refs["form"].validate((valid) => {
                    if (valid) {
                        this.btn_loading = true
                        this.form.subList = this.subList
                        if (this.form.id != null) {
                            updateFoodSafe(this.form).then((response) => {
                                this.open = false;
                                this.btn_loading = false
                                if (response.code == 200) {
                                    this.getList();
                                    this.msgSuccess("修改成功");
                                } else {
                                    this.$message.error('修改失败');
                                }
                            }).catch((err) => {
                                this.btn_loading = false
                                // this.$message.error('修改失败');
                            })

                            // $axios.put('/zyk/foodSafe', this.form).then(({ data }) => {
                            //     //请求成功，触发then中的函数
                            //     this.open = false;
                            //     this.btn_loading = false
                            //     if (data.code == 200) {
                            //         this.msgSuccess("修改成功");

                            //         this.getList();
                            //     } else {
                            //         this.btn_loading = false
                            //         this.$message.error('修改失败');
                            //     }

                            // }).catch(error =>
                            //     //请求失败，触发catch中的函数 可省略
                            //     this.$message.error('保存失败')
                            // )
                        } else {
                            try {
                                this.form.id = undefined
                            } catch (error) {

                            }
                            this.form.subList = this.subList
                            addFoodSafe(this.form).then((response) => {
                                this.btn_loading = false
                                this.open = false;
                                if (response.code == 200) {
                                    this.getList();
                                    this.msgSuccess("新增成功");
                                } else {
                                    this.$message.error('新增失败');
                                }
                            }).catch((err) => {
                                this.btn_loading = false
                                // this.$message.error('新增失败')
                            });




                            // $axios.post('/zyk/foodSafe', this.form).then(({ data }) => {
                            //     //请求成功，触发then中的函数
                            //     this.open = false;
                            //     this.btn_loading = false
                            //     if (data.code == 200) {
                            //         this.msgSuccess("新增成功");

                            //         this.getList();
                            //     } else {
                            //         this.btn_loading = false
                            //         this.$message.error('新增失败');
                            //     }

                            // }).catch(error =>
                            //     //请求失败，触发catch中的函数 可省略
                            //     this.$message.error('保存失败')
                            // )
                        }
                    }
                });
            },
            /** 删除按钮操作 */
            handleDelete(row) {
                const ids = row.id || this.ids;
                this.$confirm(
                    '是否确认删除选中的的数据项?',
                    "警告",
                    {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning",
                    }
                )
                    .then(() => {
                        delFoodSafe(ids).then((response) => {
                            if (response.code == 200) {
                                this.getList();
                                this.msgSuccess("删除成功");
                            } else {
                                this.$message.error('删除失败');
                            }
                        }).catch((err) => {

                            // this.$message.error('删除失败')
                        });

                        // $axios({
                        //     method: 'delete',
                        //     url: '/zyk/foodSafe/' + ids,

                        // }).then(res => {
                        //     this.getList();
                        //     this.msgSuccess("删除成功");

                        // })
                    })
                    .catch((err) => {
                        console.log(err)
                    });
            },

            //审批
            handleVerify(row) {
                let obj = {
                    id: row.id,
                    fzr: this.nickName
                }
                verifyFoodSafe(obj).then((response) => {
                    if (response.code == 200) {
                        this.getList();
                        this.msgSuccess("审批成功");
                    } else {
                        this.$message.error('审批失败');
                    }
                }).catch((err) => {

                    // this.$message.error('审批失败')
                });


                // $axios.post('/zyk/foodSafe/verify/' + row.id).then(({ data }) => {
                //     //请求成功，触发then中的函数
                //     if (data.code == 200) {
                //         this.msgSuccess("审批成功");

                //         this.getList();
                //     } else {
                //         this.$message.error('审批失败');
                //     }

                // }).catch(error =>
                //     //请求失败，触发catch中的函数 可省略
                //     this.$message.error('审批失败')
                // )
            },
            /** 导出按钮操作 */
            excelhandleView(row) {
                this.download(
                    "Laboratory/foodSafe/exportexcel?id=" + row.id,
                    {
                        ...this.queryParams,
                    },
                    "每日食品安全检查记录" + this.parseTime(new Date()) + ".xlsx"
                );
            },
            // 解析数据
            handleTableArr(data) {
                let arr = [];
                for (let i = 0; i < data.length; i++) {
                    let category_info = data[i];
                    let activityPointsDOS = category_info["activityPointsDOS"];
                    let count = 0;
                    // console.log(activityPointsDOS)
                    for (let j = 0; j < activityPointsDOS.length; j++) {
                        let activityTwo_info = activityPointsDOS[j];
                        count++;
                        // console.log(activityTwo_info[j])
                        let info = {
                            // 确定每天数据的 合并行的数量
                            span_num: j === 0 ? activityTwo_info.length : 0,
                            result: activityTwo_info["result"],
                            desc: activityTwo_info["desc"],
                            remark: activityTwo_info["remark"],
                            order: activityTwo_info["order"],
                            key: activityTwo_info["key"],
                            activityName: activityTwo_info["activityName"],
                            category: category_info["category"],
                        };
                        arr.push(info);
                        // let activityTwo_activityPointsDOS = activityPointsDOS[j]["activityPointsDOS"];
                        // for (let k = 0; k < activityTwo_activityPointsDOS.length; k++) {
                        //     count++;
                        //     let info = {
                        //         // 确定每天数据的 合并行的数量
                        //         span_num: k === 0 ? activityTwo_activityPointsDOS.length : 0,
                        //         value: activityTwo_activityPointsDOS[k]["value"],
                        //         message: activityTwo_activityPointsDOS[k]["message"],
                        //         activityName: activityTwo_info["activityName"],
                        //         category: category_info["category"],
                        //     };
                        //     arr.push(info);
                        // }
                    }
                    // 第一列的合并数量, 赋值给每个大项的第一个单元格. 比如合格积分要合并 8 行.
                    arr[arr.length - count]["count"] = count;
                }
                return arr;
            },
            // 表格合并的方法
            arraySpanMethod({ row, column, rowIndex, columnIndex }) {
                // 第一列
                if (columnIndex === 0) {
                    if (row.count) {
                        return [row.count, 1]
                    } else {
                        return [0, 0]
                    }
                }
                // // 第二列
                // if (columnIndex === 1) {
                //     if (row.span_num > 0) {
                //         return [row.span_num, 1]
                //     } else {
                //         return [0, 0]
                //     }
                // }
            }
        },
    };
</script>
<style>
    .myDialog .safetyRecord_form .el-form-item {
        border: none !important;
    }
</style>
<style lang="scss">
    .noGao {
        .el-table__body tr:hover>td {
            background-color: #0a366d !important;
            color: rgba(213, 241, 255, 0.8) !important;
        }
    }
</style>